//
//  TWFXAddCityViewController.m
//
//
//  Created by Lion User on 13-2-1.
//  Copyright (c) 2013年 Lion User. All rights reserved.
//

#import "TWFXAddCityViewController.h"

@interface TWFXAddCityViewController ()

@end

//获取屏幕的高度(不含状态栏)
CGFloat heightOfScreen ;//= [UIScreen mainScreen].applicationFrame.size.height;

@implementation TWFXAddCityViewController

//根据ios的延迟加载原则,一个类在创建时进行初始化的时候,在它的view被展现之前不加载
//所以在init初始化方法里不要进行涉及到self.view的操作,否则view会马上被加载,然后再执行设计到view的操作代码,就会造成view在控制器类被创建时而view还没有被展示时就被加载了
//所有涉及到self.view的操作应该放到 viewDidLoad 方法里
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"allCityInfos_new" ofType:@"plist"];
        self.allCityData = [[[NSArray alloc] initWithContentsOfFile:filePath]autorelease];
        self.searchData = [[[NSMutableArray alloc] initWithArray:self.allCityData] autorelease];
        
        
        self.navigationItem.title = @"添加城市";
        self.navigationItem.leftItemsSupplementBackButton = YES;
                
        UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"热门城市" style:UIBarButtonItemStylePlain target:self action:@selector(showFamousCity)];
        self.navigationItem.rightBarButtonItem = rightBar;
        [rightBar release];
                
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor  = [UIColor colorWithRed:211/255.0 green:211/250.0 blue:211/255.0 alpha:1];
    heightOfScreen = [UIScreen mainScreen].applicationFrame.size.height;//屏幕的高度,不含状态栏
    
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
    searchBar.showsCancelButton = NO;
    searchBar.placeholder = @"广州\\guangzhou\\gz";
    self.searchBar = searchBar;
    [self.view addSubview:searchBar];
    [searchBar release];
    
    
    UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(0.0f,44, 320.0f, heightOfScreen - 88)];
    tableview.backgroundColor = [UIColor colorWithRed:211/255.0 green:211/250.0 blue:211/255.0 alpha:1];
    self.tableview = tableview;
    [self.view addSubview:tableview];
    [tableview release];

    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.searchBar.delegate = self;
            
    
    //热门城市的view所在的scrollview
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, 320, heightOfScreen - 44)];
    self.scrollViewOfFamousCity = scrollView;
    scrollView.scrollEnabled = YES;
    scrollView.alwaysBounceVertical = NO;
    scrollView.showsVerticalScrollIndicator = YES;
    [scrollView release];
    [self.view addSubview:self.scrollViewOfFamousCity];
    
    [self initFamouseCity];

}




-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AddCityPage"];
    
    self.scrollViewOfFamousCity.alpha = 1;
}


//当前view即将退出前执行
//收起键盘
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AddCityPage"];
    
    [self searchBarResignFirstResponder];
}



#pragma mark- 热门城市的构造 开关 点击等方法

//构造热门城市
-(void)initFamouseCity
{
    //读取热门城市的数据源
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"famousCity" ofType:@"plist"];
    self.famouseCityData = [[[NSArray alloc] initWithContentsOfFile:filePath]autorelease];
    
    CGRect rectOfbtn = CGRectMake(0, 10, 80, 40);//第一个热门城市(UIButton)的原点及大小
    CFIndex heightOfFamouseCityView = (self.famouseCityData.count / 4 + 1) * rectOfbtn.size.height + rectOfbtn.origin.y + 20;//存放热门城市的view的高度
    
    
    //存放热门城市的view的fram 背景;和该view所嵌套于的scrollview
    UIView *famouseCityView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, heightOfFamouseCityView)];
    famouseCityView.backgroundColor = [UIColor colorWithRed:211/255.0 green:211/250.0 blue:211/255.0 alpha:1];
    self.scrollViewOfFamousCity.backgroundColor = famouseCityView.backgroundColor;
    self.famouseCityView = famouseCityView;
    [self.scrollViewOfFamousCity addSubview:famouseCityView];
    self.scrollViewOfFamousCity.contentSize = CGSizeMake(320, heightOfFamouseCityView + 20);
    [famouseCityView release];
    
    
    //每行放四个热门城市的button,循环数据源并确定热门城市的坐标,并加到famousCityView上
    int row = 0;
    int column = 0;
    for (int i = 0; i < self.famouseCityData.count; i++) {
        
        row = i % 4;
        column = i / 4;
        
        CGRect rect = CGRectMake(rectOfbtn.origin.x + rectOfbtn.size.width * row, rectOfbtn.origin.y + rectOfbtn.size.height * column, rectOfbtn.size.width, rectOfbtn.size.height);
        
        UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        tempBtn.frame = rect;
        [tempBtn setTitle:self.famouseCityData[i][1] forState:UIButtonTypeCustom];
        [tempBtn setTitleColor:[UIColor blackColor] forState:UIButtonTypeCustom];
        
        tempBtn.tag = i;
        [tempBtn addTarget:self action:@selector(famousCitySelected:event:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.famouseCityView addSubview:tempBtn];
    }
    
}


//热门城市 开/关 切换方法
-(void)showFamousCity
{
    if (self.scrollViewOfFamousCity.alpha == 1) {
        
        self.scrollViewOfFamousCity.alpha = 0;
        
    } else {
        
        self.scrollViewOfFamousCity.alpha = 1;
        [self searchBarResignFirstResponder];
    }

}


//热门城市uibutton 被点击时的回调方法
//根据button里的tag(索引) 来确定该热门城市的信息
-(void)famousCitySelected:(id)sender event:(UITouch *) touchEvent
{
    UIButton *tempBtn = (UIButton *)sender;
    [self addNewCity:self.famouseCityData[(int)tempBtn.tag]];
}




#pragma mark- UISearchBar 的代理方法


//如果searchBar是第一响应者,则放弃第一响应者的身份
//也就是收起键盘
-(void)searchBarResignFirstResponder
{
    if ([self.searchBar isFirstResponder]) {
        
        [self.searchBar resignFirstResponder];

    }
}



//searchbar搜索框开始输入时,也就是光标点击时,把热门城市隐藏
//这是弹起键盘的唯一途径,键盘收起则有三种可能:点击键盘的search键搜索, 点击显示热门城市, 滑动tableview里的内容
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
   // [self keyboardIsUp];
    self.scrollViewOfFamousCity.alpha = 0;
}



//点击键盘的搜索键时触发. 收起键盘即可
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self searchBarResignFirstResponder];
}


//搜索框里的text发生变化时触发该回调方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    if (searchText.length != 0)
    {
        self.scrollViewOfFamousCity.alpha = 0;
        
        NSString *searchStr = [NSString stringWithFormat:@"%@",searchText];
        
        //输入的内容是一下内容时被检索到:县名\拼音\拼音缩写以输入的内容开头;地级市名\省名 和 该内容相同
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF[1] BEGINSWITH[c] %@ OR SELF[2] == %@ OR SELF[3] == %@ OR SELF[5] == %@",searchStr,searchStr,searchStr,searchStr];
        
        self.searchData = [[[NSMutableArray alloc] initWithArray:[self.allCityData filteredArrayUsingPredicate:predicate]] autorelease];
        [self.tableview reloadData];
    }
    
}



#pragma mark- tableview 的代理方法

//滑动tableview里的内容时触发
//如果滑动tableview就把键盘收起来,那还有必要缩短tableview的高度么? 没
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    [self searchBarResignFirstResponder];
}



/*
 tableview有几个分组\section
 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}



/*
 获取tableview指定section的行数
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchData.count;
}


//tableviewCell被展示前触发.可以设置cell的背景
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row] % 2 == 1) {
        
        [cell setBackgroundColor:[UIColor colorWithRed:250/255.0 green:235/250.0 blue:215/255.0 alpha:1]];
    }
    else
    {
        [cell setBackgroundColor:[UIColor colorWithRed:230/255.0 green:230/250.0 blue:250/255.0 alpha:1]];
    }
    
}


/*
 绘制cell
 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //tableview重用cell控件 机制
    static  NSString *SimpleTableIdentifier =  @"SimpleTableIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:SimpleTableIdentifier];
        [cell autorelease];
    }
    
    NSInteger row = [indexPath row];    
    NSArray *cityInfo = nil;
    cityInfo = [self.searchData objectAtIndex:row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@  -  %@  ——  %@",cityInfo[1], cityInfo[5], cityInfo[7]];
    
    return cell;
}


/*
 可否选中某行
 把选中的城市添加到城市列表里(保存在userdefault),然后更新城市列表页面
 */
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return indexPath;
}


//选中完某一个cell之后,根据该cell的信息决定是否把它添加到城市收藏列表里
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    NSArray *cityInfo = [self.searchData objectAtIndex:row]; // 获得当前选择行
    
    [self addNewCity:cityInfo];
}




#pragma mark- 其他方法

//选中了一个城市准备添加到城市列表里
-(void)addNewCity:(NSArray *) cityInfo
{
    // 创建一个TWFXWeatherInfo类实例,并为其成员(城市名和城市编号)赋值
    TWFXStruct_AllWeatherInfo *cityWeather = [[[TWFXStruct_AllWeatherInfo alloc] init] autorelease];
    cityWeather.countID = cityInfo[0];
    cityWeather.countName = cityInfo[1];
    cityWeather.countPY = cityInfo[2];
    
    //从plist文件里读取城市信息时,信息里的地级市属性是最后一个,含有一个换行符 "\r",要去掉
    cityWeather.cityName = cityInfo[5];
    cityWeather.cityPY = cityInfo[6];
    cityWeather.proName = cityInfo[7];
    //  cityWeather.futureWeatherInfo.img_title1 = @"<#string#>"
    
    BOOL cityIsExist = NO;
    
    //citylist里是否已有该城市
    for (TWFXStruct_AllWeatherInfo* tempCity in [TWFXSingleClass sharedTWFXSingleClass].cityDataList) {
        
        if ([tempCity.countID isEqualToString:cityWeather.countID]) {
            
            cityIsExist = YES;
            break;
        }
    }
    
    //如果不存在,则添加到citylist里
    if (!cityIsExist) {
        
        [[TWFXSingleClass sharedTWFXSingleClass].cityDataList addObject:cityWeather];
        [[TWFXSingleClass sharedTWFXSingleClass] saveCityListToUserDefault];
        
        [TWFXSingleClass sharedTWFXSingleClass].isAddCity = YES; // 设置标志量,表明添加了新城市
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该城市已添加到城市列表了~" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    
    if ([self.searchBar isFirstResponder]) {
        [self.searchBar resignFirstResponder];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


//内存警告时触发
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    float sysVer =[[[UIDevice currentDevice] systemVersion] floatValue];
    
    //ios 6.0 及之后才执行以下代码,ios6.0之前是通过调用viewWillUnload来处理
    if (sysVer>= 6.0f)        
    {        
        if ([self.view window] == nil)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            
            self.tableview = nil;
            self.searchBar = nil;
            self.famouseCityView = nil;
            self.scrollViewOfFamousCity = nil;
            
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    

}



- (void)dealloc
{
    [_searchBar release];
    [_tableview release];
    self.allCityData = nil;
    self.searchData = nil;
    self.famouseCityData = nil;
    self.famouseCityView = nil;
    self.scrollViewOfFamousCity = nil;
    [super dealloc];
}



@end





